package com.zat.mes.andrmes.dofun.qualitytest

import android.app.Activity
import android.text.TextUtils
import android.view.View
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.gson.Gson
import com.tencent.bugly.proguard.s
import com.zat.mes.andrmes.R
import com.zat.mes.andrmes.base.BaseActivity
import com.zat.mes.andrmes.customerview.BottomDailog
import com.zat.mes.andrmes.customerview.BottomSignCommDialog
import com.zat.mes.andrmes.data.KvBean
import com.zat.mes.andrmes.data.LoginResultBean
import com.zat.mes.andrmes.data.ParantTypeItem
import com.zat.mes.andrmes.data.QcRecordBean
import com.zat.mes.andrmes.dofun.qualitytest.adapter.OnSiteDetailAdapter
import com.zat.mes.andrmes.dofun.qualitytest.vm.QcPlanViewModel
import com.zat.mes.andrmes.global.CompanionType
import com.zat.mes.andrmes.utils.PreferencesUtil
import com.zat.mes.andrmes.utils.SpannableStrUtil
import com.zat.mes.andrmes.utils.showToast
import kotlinx.android.synthetic.main.activity_on_site_detail.*
import kotlinx.android.synthetic.main.layout_title.*
import org.json.JSONObject

/**
 * 巡检详情
 */
class OnSiteDetailActivity : BaseActivity(), View.OnClickListener {

    private var qcPlanViewModel: QcPlanViewModel? = null
    private var empId: Long = 0
    private var empName: String = ""
    var qcType: Int = 0
    var bean: QcRecordBean? = null
    var reasonStr: String = ""
    var reasonType: String = ""
    var dealWith: String = ""
    var bodypart:String = ""
    var listReason: MutableList<ParantTypeItem>? = null
    var selectReason: MutableList<ParantTypeItem> = ArrayList()
    var listDealWith: MutableList<ParantTypeItem>? = null
    var selectDealWith: MutableList<ParantTypeItem> = ArrayList()
    var listBodyPath: MutableList<ParantTypeItem>? = null
    var selectBodyPosition:Int = -1
    /**
     * 1合格 0不合格
     */
    var result: String = "1"

    override fun init() {
        initView()
        iniData()
        addListener()
        loadModel()
    }

    private fun loadModel() {
        qcPlanViewModel = ViewModelProvider(this).get(QcPlanViewModel::class.java)
        qcPlanViewModel?.getParantTypeData()?.observe(this, Observer {
            if (it != null) {
                if (it.containsKey(CompanionType.QC_DEFECTIVE)) {
                    //原因
                    listReason = it.get(CompanionType.QC_DEFECTIVE)
                }
                if (it.containsKey(CompanionType.QC_TREATMENT)) {
                    //处置方式
                    listDealWith = it.get(CompanionType.QC_TREATMENT)

                }
                if(it.containsKey(CompanionType.STYLE_BODYPART)){
                    //部位
                    listBodyPath = it.get(CompanionType.STYLE_BODYPART)
                }
            }
        })
        qcPlanViewModel?.loadParantTypeList(CompanionType.QC_DEFECTIVE)
        llBadDealWith.postDelayed(Runnable {
            qcPlanViewModel?.loadParantTypeList(CompanionType.QC_TREATMENT)
        }, 500)
        llBadDealWith.postDelayed({
            qcPlanViewModel?.loadParantTypeList(CompanionType.STYLE_BODYPART)
        },500)

        qcPlanViewModel?.getInsertData()?.observe(this, Observer {
            closeLoading()
            if (it != null && getString(R.string.post_success).equals(it)) {
                showToast(it)
                setResult(Activity.RESULT_OK)
                finish()
            }
        })
    }

    /**
     * 初始化数据
     */
    private fun iniData() {

        val loginResultBean = Gson().fromJson(
            PreferencesUtil.getString(CompanionType.LOGIN_RESULT),
            LoginResultBean::class.java
        )
        empId = loginResultBean.empid
        empName = loginResultBean.empname
        val onSiteDetailAdapter = OnSiteDetailAdapter(R.layout.item_de_approve)
        ryOnSiteDetail.layoutManager = LinearLayoutManager(this)
        ryOnSiteDetail.adapter = onSiteDetailAdapter

        qcType = intent.getIntExtra(CompanionType.INTENT_EXTRA_QCTYPE, 0)
        val list: MutableList<KvBean> = ArrayList()
        bean = intent.getParcelableExtra(CompanionType.INTENT_EXTRA_BEAN) as QcRecordBean
        if (!TextUtils.isEmpty(bean?.clothesqRcode)){
            etQualityOnsite.setText("1")
            etBadQualityOnsite.setText("1")
        }
        val kv1 = bean?.productName?.let {
            KvBean(
                getString(R.string.produce_name),
                it
            )
        }
        kv1?.let { list.add(it) }
        val kv2 = bean?.styleNO?.let {
            KvBean(
                getString(R.string.text_style),
                it
            )
        }
        kv2?.let { list.add(it) }
        val kv3 = bean?.color?.let { KvBean(getString(R.string.text_color), it) }
        kv3?.let { list.add(it) }
        val kv4 = bean?.size?.let { KvBean(getString(R.string.text_size), it) }
        kv4?.let { list.add(it) }
        val kv5 = bean?.procName?.let {
            KvBean(
                getString(R.string.text_proc),
                it
            )
        }
        kv5?.let { list.add(it) }
        val kv6 = bean?.workshopname?.let {
            KvBean(
                getString(R.string.text_workshop),
                it
            )
        }
        kv6?.let { list.add(it) }
        val kv7 = bean?.classname?.let {
            KvBean(
                getString(R.string.text_class),
                it
            )
        }
        kv7?.let { list.add(it) }
        val kv8 = bean?.empName?.let {
            KvBean(
                getString(R.string.text_peple),
                it
            )
        }
        kv8?.let { list.add(it) }
        val kv9 =
            KvBean(getString(R.string.text_amount), bean?.quantity.toString())
        list.add(kv9)
        onSiteDetailAdapter.setNewData(list)


    }

    private fun addListener() {
        rgOnsite.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                rbOkOnsite.id -> {
                    llShowOnsite.visibility = View.GONE
                    result = "1"
                }
                rbNoOkOnsite.id -> {
                    llShowOnsite.visibility = View.VISIBLE
                    result = "0"
                }
            }
        }
    }

    private fun initView() {
        setContentView(R.layout.activity_on_site_detail)
        tVtitle.text = getString(R.string.title_on_site)
        rlReturnTitle.visibility = View.VISIBLE
        rlReturnTitle.setOnClickListener(this)
        btnOnSiteDetail.setOnClickListener(this)
        llBadReason.setOnClickListener(this)
        llBadDealWith.setOnClickListener(this)
        llBody.setOnClickListener(this)
        tvQualityOnsite.setText(
            SpannableStrUtil.getColorSpannable(
                getString(R.string.check_amount_x),
                0,
                1,
                ContextCompat.getColor(this, R.color.color_text_red)
            )
        )
        tvBadQualityOnsite.setText(
            SpannableStrUtil.getColorSpannable(
                getString(R.string.bad_produce_amount_x),
                0,
                1,
                ContextCompat.getColor(this, R.color.color_text_red)
            )
        )
    }

    override fun onClick(v: View?) {
        when (v) {
            rlReturnTitle -> finish()
            btnOnSiteDetail -> {
                if (TextUtils.isEmpty(etQualityOnsite.text.toString())) {
                    showToast(getString(R.string.text_input_check_amout))
                    return
                }
                if (TextUtils.isEmpty(etBadQualityOnsite.text.toString()) && llShowOnsite.visibility == View.VISIBLE) {
                    showToast(getString(R.string.text_input_bad_amount))
                    return
                }
                //接口传参
                val jsonObject = JSONObject()
                jsonObject.put("factoryId", bean?.factoryId)
                jsonObject.put("workshopId", bean?.workshopid)
                jsonObject.put("workshopName", bean?.workshopname)
                jsonObject.put("classId", bean?.classid)
                jsonObject.put("className", bean?.classname)
                jsonObject.put("qcplanId", bean?.jhId)
                jsonObject.put("qcType", qcType)
                jsonObject.put("produceId", bean?.produceId)
                jsonObject.put("packNO", bean?.packNo)
                jsonObject.put("orderId", bean?.orderId)
                jsonObject.put("styleNo", bean?.styleNO)
                jsonObject.put("productName", bean?.productName)
                jsonObject.put("color", bean?.color)
                jsonObject.put("size", bean?.size)
                jsonObject.put("procId", bean?.procId)
                jsonObject.put("procName", bean?.procName)
                jsonObject.put("workEmpId", bean?.empId)
                jsonObject.put("workEmpName", bean?.empName)
                jsonObject.put("quantity", bean?.quantity)
                jsonObject.put("qcQty", etQualityOnsite.text.toString())
                jsonObject.put("qcEmpId", empId)
                jsonObject.put("qcEmpName", empName)
                jsonObject.put("result", result)
                jsonObject.put("publicQRCode",bean?.publicQRCode)
                jsonObject.put("publicRFID",bean?.publicRFID)
                jsonObject.put("packId",bean?.packId)
                if ("0".equals(result)) {
                    jsonObject.put("NGQty", etBadQualityOnsite.text.toString())
                    jsonObject.put("NGReason", reasonStr)
                    jsonObject.put("NGReasonCode", reasonType)
                    jsonObject.put("NGDeal", dealWith)
                    jsonObject.put("remark1", etBadRemark.text.toString())
                    jsonObject.put("bodypart",bodypart)
                }

                showLoading()
                qcPlanViewModel?.insertQcRecord(jsonObject.toString())

            }
            llBadReason -> showBottomDialog(true, listReason,selectReason)
            llBadDealWith -> showBottomDialog(false, listDealWith,selectDealWith)
            llBody->showBodyDialog(listBodyPath,selectBodyPosition)
        }
    }
    //弹框 原因
    fun showBottomDialog(reason: Boolean,list: MutableList<ParantTypeItem>?, selectList:MutableList<ParantTypeItem>) {
        BottomDailog(this, list,selectList, object : BottomDailog.OnBottomSelectListener {
            override fun onBottomSelect(list: MutableList<ParantTypeItem>) {
                if (reason) {
                    val str = StringBuilder()
                    val strType = StringBuilder()
                    for (index in list.indices) {
                        str.append(list.get(index).typename)
                        if (index!=list.size-1) {
                            str.append(",")
                        }
                        strType.append(list.get(index).typeid)
                        if (index!=list.size-1) {
                            strType.append(",")
                        }
                    }
                    reasonStr = str.toString()
                    reasonType = strType.toString()
                    tbBadReason.text = reasonStr
                    selectReason = list
                } else {
                    val deal = StringBuilder()
                    for (index in list.indices) {
                        deal.append(list.get(index).typename)
                        if (index!=list.size-1) {
                            deal.append(",")
                        }
                    }
                    dealWith = deal.toString()
                    tbBadDealWith.text = dealWith
                    selectDealWith = list
                }
            }

        })
    }

    /**
     * 部位 弹框
     */
    fun showBodyDialog(list: MutableList<ParantTypeItem>?,selectPosition: Int) {
        val strList: MutableList<String> = ArrayList()
        if (list != null) {
            for (type in list) {
                strList.add(type.typename)
            }
        }
        BottomSignCommDialog(this, strList,selectPosition, object : BottomSignCommDialog.OnBottomSelectListener {
            override fun onBottomSelect(position: Int) {
                if(position>=0) {
                    tbBody.text = list?.get(position)?.typename
                    bodypart = list?.get(position)?.typecode.toString()
                    selectBodyPosition = position
                }
            }

        })
    }

}
